package liurong.driver.thread;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class Cache2Test {

	private static final ConcurrentHashMap<String, Semaphore> CACHE_SEMAPHORE = new ConcurrentHashMap<String, Semaphore>();

	private static final ExecutorService EXECUTORS = Executors.newFixedThreadPool(100);

	public static void main(String[] args) throws InterruptedException {

		final AtomicInteger atomicInteger = new AtomicInteger();

		// 模拟能得到缓存
		final AtomicBoolean flag = new AtomicBoolean(false);

		for (int i = 0; i < 100; i++) {
			final String key = getKey(i);
			EXECUTORS.execute(new Runnable() {
				@Override
				public void run() {
					Semaphore semaphore = CACHE_SEMAPHORE.putIfAbsent(key, getSemaphore());
					if (semaphore == null) {// 第一次设置必然为null，所以这里防止第一次获取为null
						semaphore = CACHE_SEMAPHORE.get(key);
					}
					try {
						if (semaphore.tryAcquire()) {
							synchronized (semaphore) {
								if (flag.get()) {
									atomicInteger.incrementAndGet();
								}
								System.out.println("设置缓存！");
								flag.compareAndSet(false, true);
							}
							semaphore.release();
						} else {
							synchronized (semaphore) {
								atomicInteger.incrementAndGet();
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}

		Thread.sleep(2000);
		System.out.println(atomicInteger);
	}

	private static String getKey(int i) {
		String key;
		if (i % 3 == 0) {
			key = "key0";
		} else if (i % 3 == 1) {
			key = "key1";
		} else {
			key = "key2";
		}
		return key;
	}

	/**
	 * 得到唯一一个信号量
	 * 
	 * @return
	 */
	public static Semaphore getSemaphore() {
		return new Semaphore(1);
	}
}
